package chapters19;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by xinxuchu on 2020/2/7.
 *
 * CyclicBarrier 多线程集合点应用案例
 *
 * 在项目中其实可以广泛应用，尤其在应对年度数据汇总的时候
 */
public class CyclicBarrierDemo {

    static class Tourist extends Thread{
        CyclicBarrier barrier;

        public Tourist(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run(){
            try {
                //模拟各自先独立运行
                Thread.sleep((int)(Math.random()*1000));
                //集合点A
                barrier.await();
                System.out.println(getName()+" Arrived A "+System.currentTimeMillis());
                //集合后再模拟各自运行
                Thread.sleep((int)(Math.random()*1000));
                //集合点B
                barrier.await();
                System.out.println(getName()+" Arrived B "+System.currentTimeMillis());
            }catch (InterruptedException e){
            }catch (BrokenBarrierException e){
            }
        }
    }

    public static void main(String[] args) {
        int num = 3;
        Tourist[] tourists = new Tourist[num];
        CyclicBarrier barrier = new CyclicBarrier(num, new Runnable() {
            @Override
            public void run() {
                System.out.println("all arrived "+System.currentTimeMillis()+" exected by "+Thread.currentThread().getName());
            }
        });

        for (int i = 0; i < num; i++) {
            tourists[i] = new Tourist(barrier);
            tourists[i].start();
        }
    }
}
